package com.das.mechanic_base.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.mapi.schedulers.RxSchedulersHelper;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class FusedLocationUtils {

    private Context mContext;
    private LocationManager locationManager;
    private Location lastKnownLocation;

    private String locationProvider;

    public FusedLocationUtils(Context mContext) {
        this.mContext = mContext;
    }

    public void startLocation() {
        boolean isChina = X3Constent.isChina();

        // 51.491806  -0.061090
//        requestLocationGaoDe();
        requestLocationGoogle();
    }

    private boolean isStart = true;
    private void requestLocationGoogle() {
        XXPermissions.with(mContext)
                .permission(Permission.ACCESS_COARSE_LOCATION)
                .permission(Permission.ACCESS_FINE_LOCATION)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if(all){
                            locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);

                            List<String> providers = locationManager.getProviders(true);

                            if (providers.contains(LocationManager.GPS_PROVIDER)) {
                                //如果是GPS
                                locationProvider = LocationManager.GPS_PROVIDER;
                            } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
                                //如果是Network
                                locationProvider = LocationManager.NETWORK_PROVIDER;
                            } else {
                                if(isStart){
                                    new Handler().postDelayed(() -> {
                                        if (iOnGetLocation != null) {
                                            iOnGetLocation.iOnGetLocationFailed();
                                            isStart = false;
                                        }
                                    },200);
                                }
                                return;
                            }

                            if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                                return;
                            }
                            locationManager.requestLocationUpdates(locationProvider, 3000, 1, locationListener);
                            lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);

                            if (lastKnownLocation != null) {
                                startGetLocation(lastKnownLocation);
                            }else {
                                getLngAndLatWithNetwork();
                            }
                        }else{
                            XXPermissions.startPermissionActivity(mContext, permissions);
                            if (iOnGetLocation != null) {
                                iOnGetLocation.iOnGetLocationFailed();
                            }
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        XXPermissions.startPermissionActivity(mContext, permissions);
                        if (iOnGetLocation != null) {
                            iOnGetLocation.iOnGetLocationFailed();
                        }
                    }
                });
    }

    public LocationListener locationListener = new LocationListener() {

        private double latitude;
        private double longitude;

        // Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        // Provider被enable时触发此函数，比如GPS被打开
        @Override
        public void onProviderEnabled(String provider) {
        }

        // Provider被disable时触发此函数，比如GPS被关闭
        @Override
        public void onProviderDisabled(String provider) {
        }

        //当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
        @Override
        public void onLocationChanged(Location location) {
            if (location != null) {
                if(longitude != location.getLongitude() || latitude != location.getLatitude()){
                    longitude = location.getLongitude();
                    latitude = location.getLatitude();
                    startGetLocation(location);
                        //如果位置发生变化，重新显示地理位置经纬度
                        //Log.e("SSSS", "监视地理位置变化-经纬度：" + location.getLongitude() + "   " + location.getLatitude());
                }
            }
        }
    };


    private void startGetLocation(Location location) {
        if (iOnGetLocation != null) {
            iOnGetLocation.iOnGetLocationFailed();
        }
        Observable.create((ObservableOnSubscribe<String>) e -> {
            //51.491806  -0.061090
            String address = getAddress(location.getLatitude(), location.getLongitude());
            e.onNext(address);
        }).map(address -> address)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String locationBean) {
                        if (iOnGetLocation != null) {
                            iOnGetLocation.iOnGetLocationSuccess(locationBean);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (iOnGetLocation != null) {
                            iOnGetLocation.iOnGetLocationFailed();
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 逆地理编码 耗时任务 需要子线程进行
     * @param latitude
     * @param longitude
     * @return
     */
    private String getAddress(double latitude, double longitude) {

        Geocoder geoCoder = new Geocoder(mContext, Locale.CHINESE);
        try {
            List<Address> addressList = geoCoder.getFromLocation(
                    latitude, longitude,
                    1);

            if (X3StringUtils.isListEmpty(addressList)) {
                return "";
            }
            Address address = addressList.get(0);

            int maxAddressLineIndex = address.getMaxAddressLineIndex();
            if (maxAddressLineIndex >= 2) {
                return address.getAddressLine(0) + address.getAddressLine(1);
            }else {
                return address.getAddressLine(0);
            }
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("SSS","获取地址报错:" + e.toString());
        }


//        Locale appLocale = LanguageUtiles.getAppLocale(LanguageUtiles.appContext).locale;
//
//        Request request = new Request.Builder()
//                .url(String.format(mContext.getString(R.string.x3_google_geocode_url), latitude + "," + longitude,
//                        appLocale.getLanguage() + "-" + appLocale.getCountry(), mContext.getString(R.string.x3_google_maps_key)))
//                .build();
//
//        try {
//            Response response = new OkHttpClient().newCall(request).execute();
//            String address = response.body().string();
//            if (X3StringUtils.isEmpty(address)) {
//                return "";
//            }
//            GoogleGeocoderBean googleGeocoderBean = new Gson().fromJson(address, GoogleGeocoderBean.class);
//            List<GoogleGeocoderBean.ResultsBean> results = googleGeocoderBean.getResults();
//            if (X3StringUtils.isListEmpty(results)) {
//                return "";
//            }
//            String address_components = results.get(0).getFormatted_address();
//            return address_components;
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        return "";
    }

    public void onDestory() {
        if (locationManager != null) {
            locationManager.removeUpdates(locationListener);
        }
    }

    //从网络获取经纬度
    private void getLngAndLatWithNetwork() {
        XXPermissions.with(mContext)
                .permission(Permission.ACCESS_COARSE_LOCATION)
                .permission( Permission.ACCESS_FINE_LOCATION)
                .request(new OnPermissionCallback() {
                    @SuppressLint("MissingPermission")
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if(all){
                            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 1, locationListener);
                            lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                            if (lastKnownLocation != null) {
                                startGetLocation(lastKnownLocation);
                            }
                        }else {
                            XXPermissions.startPermissionActivity(mContext,permissions);
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        XXPermissions.startPermissionActivity(mContext,permissions);
                    }
                });
    }

    IOnGetLocation iOnGetLocation;

    public void setiOnGetLocation(IOnGetLocation iOnGetLocation) {
        this.iOnGetLocation = iOnGetLocation;
    }

    public interface IOnGetLocation {
        /**
         * 获取定位成功
         */
        void iOnGetLocationSuccess(String locationBean);

        /**
         * 获取定位失败 1失败
         */
        void iOnGetLocationFailed();
    }

    public static boolean isLocServiceEnable(Context context) {
        LocationManager locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        return gps || network;
    }
    public static void goToLocation(Context context){
        // 定位服务页面
        Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        context.startActivity(intent);
    }

}
